import mqtt from 'mqtt'
import storage from './storage'

let client = null
export const connectMQTT = () => {
  const brokerUrl = 'ws://localhost:31554/mqtt' // 配置你的 broker 地址
  const storedClientId = storage.get('mqttClientId')
  const clientId = storedClientId || 'mqtt_vue_client_' + Math.random().toString(16).substr(2, 8)
  const options = {
    connectTimeout: 10000,
    clientId: clientId, // 随机生成客户端ID
    username: 'admin', // EMQX 用户名（如果需要）
    password: 'hhuc1115', // EMQX 密码（如果需要）
    clean: false, // 保证客户端断开后不会收到离线消息
    keepalive: 30,
  }

  client = mqtt.connect(brokerUrl, options)

  storage.set('mqttClientId', clientId)

  client.on('connect', () => {
    // console.log('MQTT Connected')
  })

  client.on('message', (topic, message) => {
    console.log(`Received message on ${topic}: ${message.toString()}`)
  })

  client.on('error', (err) => {
    console.error('MQTT Connection error: ', err)
  })

  client.on('close', () => {
    console.log('MQTT Disconnected')
  })

  return client
}

export const getMQTTClient = () => client
